package be.nepherte.movmanager.client.ui.components;

import java.util.List;

import be.nepherte.movmanager.client.util.StringUtil;
import be.nepherte.movmanager.domain.Genre;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;

public class GenreBox extends Composite implements 	HasValues<Genre> {
	/**Text box where genre strings are put in.*/
	private final TextBox genreBox = new TextBox();
	/**Genre picker associated with this genre box.*/
	private final GenrePicker genrePicker = new GenrePicker();
	
	/**
	 * Creates a new GenreBox.
	 */
	public GenreBox() {
		GenreBoxHandler handler = new GenreBoxHandler();
		genreBox.addClickHandler(handler);
		genrePicker.addValueChangeHandler(handler);
		initWidget(genreBox);
	}
	
	@Override
	public List<Genre> getValue() {
		List<String> genresString = StringUtil.split(genreBox.getText(), ", ");
		return Genre.getGenres(genresString);
	}
	
	@Override
	public void addValue(Genre value) {
		addValue(value, false);
	}
	
	@Override
	public void addValue(Genre value, boolean fireEvent) {
		List<Genre> values = getValue();
		if (value != null && !values.contains(value)) {
			String oldValue = genreBox.getText();
			genreBox.setText(oldValue.isEmpty() ? value.toString() : oldValue + ", " + value.toString());
			if (fireEvent)
				ValueChangeEvent.fire(this, getValue());
		}
	}
	
	@Override
	public void setValue(List<Genre> values) {
		setValue(values, false);
	}
	
	@Override
	public void setValue(List<Genre> values, boolean fireEvent) {
		if (values == null) {
			genreBox.setText("");
			return;
		}

		List<Genre> oldValues = getValue();
		genreBox.setText(StringUtil.toString(values, " ,"));

		if (fireEvent)
			ValueChangeEvent.fireIfNotEqual(this, oldValues, values);
	}
	
	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<Genre>> handler) {
		return addHandler(handler, ValueChangeEvent.getType());
	}

	/**
	 * Handler for this GenreBox.
	 *
	 * @author	Bart Verhoeven
	 * @version	0.1
	 */
	private class GenreBoxHandler implements ClickHandler, ValueChangeHandler<Genre> {

		@Override
		public void onClick(ClickEvent event) {
			showGenrePicker();
		}
		
		@Override
		public void onValueChange(ValueChangeEvent<Genre> event) {
			addValue(genrePicker.getValue());
		}

		/**
		 * Shows the genre picker.
		 */
		private void showGenrePicker() {
			PopupPanel pp = new PopupPanel(true);
			pp.setWidget(genrePicker);
			pp.setPopupPosition(genreBox.getAbsoluteLeft() + 310, genreBox.getAbsoluteTop());
			pp.show();
		}
	}
}
